<script setup lang="ts">
import { computed, inject, ref } from 'vue'
import API from '@renderer/api/constant'
import { post, postWithAns } from '@renderer/api/http'
import pinyin from 'pinyin'
import importSvg from '@renderer/assets/imgs/import.svg'
import exportSvg from '@renderer/assets/imgs/export.svg'
import refreshSvg from '@renderer/assets/imgs/refresh.svg'
import addSvg from '@renderer/assets/imgs/add.svg'
import deleteSvg from '@renderer/assets/imgs/delete.svg'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { GlobalNotification } from '@renderer/components/Toast/GlobalNotification'


const { patientListRef, getPatientList } = inject('patients') as any
const detailNameFlag = ref(false)

const {
  addPatientVisibleRef,
  confirmPatientVisibleRef,
  selectedPatientRef,
  historyImgModalVisibleRef,
  showHistoryPatientIds
} = inject('patients') as any

getPatientList()
const handleFresh = () => {
  getPatientList()
}

const searchValRef = ref('')

const handleNameSort = (a: any, b: any, key: any) => {
  return pinyin.compare(a[key], b[key])
}
const transformName = (patientName) => {
  if (patientName.length >= 2) {
    const first = patientName.substr(0, 1)
    const last = patientName.substr(-1, 1)
    return `${first}*${last}`
  } else if (patientName.length === 1) {
    const first = patientName.substr(0, 1)
    return `${first}**`
  } else {
    return `**`
  }
}

const getRowKey = () => {
}

const handleFindImg = (scope: any) => {
  console.log(scope.row.patientId)
  showHistoryPatientIds.value = [scope.row.patientId]
  historyImgModalVisibleRef.value = true
}

const handleCurrentChange = (row) => {
  confirmPatientVisibleRef.value = true
  selectedPatientRef.value = row
}

const handleAdd = () => {
  selectedPatientRef.value = {}
  addPatientVisibleRef.value = true
}

const showConfirmDelete = () => {
  ElMessageBox.confirm(
    '确定删除选中的患者?',
    'Warning',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  )
    .then(() => {
      const ids = patientsMultiSelectRef.value.map((eachPatient: any) => {
        return eachPatient.patientIndex
      })
      postWithAns(API.deletePatient, () => {
        GlobalNotification({
          message: '删除成功',
          type: 'success',
          duration: 1000
        })
        handleFresh()
        patientTableRef.value.clearSelection()
      }, {
        patientIDList: ids
      })
    })
    .catch(() => {

    })
}

const patientsMultiSelectRef = ref([])

const handleSelectionChange = (val) => {
  patientsMultiSelectRef.value = val
}


const filterTableData = computed(() => {
  return patientListRef.value.filter(
    (data: any) =>
      !searchValRef.value ||
      data.patientName.toLowerCase().includes(searchValRef.value.toLowerCase()) ||
      data.patientIndex.toString().toLowerCase().includes(searchValRef.value.toString().toLowerCase()) ||
      data.patientId.toLowerCase().includes(searchValRef.value.toLowerCase()) ||
      data.referencePhysicianName.toLowerCase().includes(searchValRef.value.toLowerCase())
  )
})

const patientTableRef = ref()
</script>

<template>
  <div>
    <div class="flex">
      <el-input
        v-model="searchValRef"
        style="width: 240px"
        placeholder="输入关键字"
        clearable
        class="mr-auto"
      >
        <template #prefix>
          <el-icon class="el-input__icon">
            <search />
          </el-icon>
        </template>
      </el-input>
      <div style="width: 20px;display: flex;align-items: center;margin-right: 10px"
           @click="detailNameFlag = !detailNameFlag">
        <img v-if="detailNameFlag" style="width: 100%" src="@renderer/assets/imgs/eye-close.png">
        <img v-else style="width: 100%" src="@renderer/assets/imgs/eye-open.png">
      </div>
      <el-button>
        <import-svg />
        <span>
          导入
        </span>
      </el-button>
      <el-button>
        <export-svg />
        <span>导出</span>
      </el-button>
      <el-button @click="handleFresh">
        <refresh-svg />
        <span>刷新列表</span>
      </el-button>
      <el-button @click="handleAdd">
        <add-svg />
        <span>添加</span>
      </el-button>
      <el-button type="warning" @click="showConfirmDelete" :disabled="patientsMultiSelectRef.length  === 0">
        <delete-svg />
        <span>删除</span>
      </el-button>
    </div>
    <el-card>
      <el-table
        ref="patientTableRef"
        :data="filterTableData"
        :default-sort="{ prop: 'date', order: 'descending' }"
        style="width: 100%"
        size="small"
        stripe
        :row-style="{height: '60px'}"
        :row-key="getRowKey"
        max-height="500"
        highlight-current-row
        @row-click="handleCurrentChange"
        @selectionChange="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="30"
          reserve-selection
        >
        </el-table-column>

        <el-table-column
          property="patientIndex"
          sortable
          :label="$t(`patients.patientIndex`)"
        >
        </el-table-column>

        <el-table-column
          property="patientId"
          sortable
          :label="$t(`patients.patientId`)"
        >
        </el-table-column>

        <el-table-column
          prop="patientName"
          sortable
          :sort-method="(a,b) => handleNameSort(a,b,'patientName')"
          :label="$t(`patients.patientName`)"
        >
          <template #default="scope">
            <span v-if="scope.row.patientName === '急诊患者'">{{ scope.row.patientName }}</span>
            <span v-else-if="detailNameFlag">{{ scope.row.patientName }}</span>
            <span v-else>{{ transformName(scope.row.patientName) }}</span>
          </template>
        </el-table-column>


        <el-table-column
          prop="gender"
          width="100"
          :label="$t(`patients.gender`)"
          sortable
        >
          <template #default="scope">
            <span v-if="scope.row.gender === 0">{{ $t('common.man') }}</span>
            <span v-else-if="scope.row.gender ===1">{{ $t('common.woman') }}</span>
            <span v-else>{{ $t('common.other') }}</span>
          </template>
        </el-table-column>


        <el-table-column
          prop="age"
          width="100"
          sortable
          :label="$t(`patients.age`)"
        >
        </el-table-column>

        <el-table-column
          sortable
          width="150"
          :sort-method="(a,b) => handleNameSort(a,b,'referencePhysicianName')"
          prop="referencePhysicianName"
          :label="$t(`patients.referencePhysicianName`)"
        >
        </el-table-column>


        <el-table-column
          prop="hasImg"
          sortable
          :label="$t(`patients.history_img`)"
        >
          <template #default="scope">
            <template v-if="scope.row.hasImg===1">
              <el-button text @click.stop="handleFindImg(scope)">
                <div class="h-[50px] ">
                  <img class="h-full" src="@renderer/assets/imgs/history_img.png">
                </div>
              </el-button>
            </template>
            <template v-else>
              <div style="width: 60px;display: flex;justify-content: center">
                <span>{{ $t('patients.notice_no_history') }}</span>
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<style scoped>
</style>
